//
//  GroupListViewController.m
//  SportSocial
//
//  Created by yull on 15/1/16.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "GroupListViewController.h"
#import "NearGroupCell.h"
#import "GroupNet.h"
#import "GroupInfoViewController.h"
#import "GroupCreateViewController.h"

@interface GroupListViewController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *groupTableView;
@property (nonatomic, strong) NSMutableArray *groupArray;

@property (nonatomic, strong) NearGroup *operatingGroup;

@end

@implementation GroupListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavibar];
    
    [self initTableView];
    
    [self getGroupList];
}

- (void)initNavibar
{
    [self addCommonBackButton];
    
    self.navigationItem.title = @"我的俱乐部";
}

- (void)initTableView
{
    CGRect rect = CGRectMake(0, 0, self.view.width, self.view.height - Navibar_Height);
    self.groupTableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    self.groupTableView.delegate = self;
    self.groupTableView.dataSource = self;
    self.groupTableView.backgroundColor = [UIColor clearColor];
    self.groupTableView.separatorInset = UIEdgeInsetsZero;
    [self.view addSubview:self.groupTableView];
    
    self.groupTableView.tableFooterView = [[UIView alloc] init];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.groupArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [NearGroupCell nearGroupCellHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"GroupCell";
    NearGroupCell *groupCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!groupCell) {
        groupCell = [[NearGroupCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        groupCell.distanceLabel.hidden = YES;
    }
    
    NearGroup *nearGroup = [self.groupArray objectAtIndex:indexPath.row];
    [groupCell drawCellWithNearGroup:nearGroup];
    return groupCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NearGroup *nearGroup = [self.groupArray objectAtIndex:indexPath.row];
    GroupInfoViewController *groupInfo = [[GroupInfoViewController alloc] initWithNearGroup:nearGroup];
    [self.navigationController pushViewController:groupInfo animated:YES];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NearGroup *nearGroup = [self.groupArray objectAtIndex:indexPath.row];
    if (nearGroup.creator_id == [CurrentUser shareInstance].userId) {
        return @"解散";
    }
    
    return @"删除";
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NearGroup *nearGroup = [self.groupArray objectAtIndex:indexPath.row];
    self.operatingGroup = nearGroup;
    
    if (nearGroup.creator_id == [CurrentUser shareInstance].userId) {
        [self dismissMyGroup:nearGroup.group_id];
    } else {
        [self quitGroup:nearGroup.group_id];
    }

}

#pragma mark - Net
- (void)dismissMyGroup:(UInt64)groupId
{
    [self showHUD];
    
    @weakify(self);
    [GroupNet dismissGroupWithGroupId:groupId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        [self showHUD];
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            
            [self.groupArray removeObject:self.operatingGroup];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.groupTableView reloadData];
                
                UIButton *rightButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
                rightButton1.frame = CGRectMake(0, 0, 60, 26);
                [rightButton1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [rightButton1 setTitle:@"创建" forState:UIControlStateNormal];
                [rightButton1 addTarget:self action:@selector(onCreateGroup:) forControlEvents:UIControlEventTouchUpInside];
                UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithCustomView:rightButton1];
                self.navigationItem.rightBarButtonItem = rightItem1;
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)quitGroup:(UInt64)groupId
{
    [self showHUD];
    
    @weakify(self);
    [GroupNet quitGroupWithGroupId:groupId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        [self showHUD];
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            
            [self.groupArray removeObject:self.operatingGroup];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.groupTableView reloadData];
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)getGroupList
{
    if (!self.groupArray) {
        self.groupArray = [NSMutableArray array];
    }else {
        [self.groupArray removeAllObjects];
    }
    
    @weakify(self);
    [GroupNet getUserGroupWithSuccessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSArray *dictArray = [responseObject objectForKey:@"data"];
            for (NSDictionary *dict in dictArray) {
                [self.groupArray addObject:[NearGroup nearGroupWithDict:dict]];
            }
            
            BOOL hasCreated = NO;
            for (NearGroup *group in self.groupArray) {
                if (group.creator_id == [CurrentUser shareInstance].userId) {
                    hasCreated = YES;
                    break;
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.groupTableView reloadData];
                
                if (hasCreated) {
                    UIButton *rightButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
                    rightButton1.frame = CGRectMake(0, 0, 60, 26);
                    [rightButton1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [rightButton1 setTitle:@"修改" forState:UIControlStateNormal];
                    [rightButton1 addTarget:self action:@selector(onCreateGroup:) forControlEvents:UIControlEventTouchUpInside];
                    UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithCustomView:rightButton1];
                    self.navigationItem.rightBarButtonItem = rightItem1;
                } else {
                    UIButton *rightButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
                    rightButton1.frame = CGRectMake(0, 0, 60, 26);
                    [rightButton1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [rightButton1 setTitle:@"创建" forState:UIControlStateNormal];
                    [rightButton1 addTarget:self action:@selector(onCreateGroup:) forControlEvents:UIControlEventTouchUpInside];
                    UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithCustomView:rightButton1];
                    self.navigationItem.rightBarButtonItem = rightItem1;
                }
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)onCreateGroup:(id)sender
{
    GroupCreateViewController *createViewController = [[GroupCreateViewController alloc] init];
    
    for (NearGroup *group in self.groupArray) {
        if (group.creator_id == [CurrentUser shareInstance].userId) {
            createViewController.group = group;
            break;
        }
    }
    
    [self.navigationController pushViewController:createViewController animated:YES];
}

@end
